<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle">
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="primary" @click="handleSubmit(false)">保存</a-button>
      <a-button v-if="!isUpdate" type="primary" @click="handleSubmit(true)"
        >保存并继续添加</a-button
      >
    </template>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '@/components/Modal';
import { BasicForm, useForm } from '@/components/Form/index';
import { dataFormSchema } from './dict.data';
import { useMessage } from '@/hooks/web/useMessage';
import { editSysDictData, addSysDictData } from '@/api/sys/sysDictDataManage';
import { useI18n } from '@/hooks/web/useI18n';
const props = defineProps({
  typeId: String,
});
const emit = defineEmits(['success', 'register']);
let isUpdate = ref(true);
const { t } = useI18n();

const { createMessage } = useMessage();
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 100,
  schemas: dataFormSchema,
  baseColProps: { span: 24 },
  showActionButtonGroup: false,
});

const [registerModal, { setModalProps, closeModal }] = useModalInner(
  async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
  }
);

const getTitle = computed(() =>
  !unref(isUpdate) ? t('新增字典') : t('编辑字典')
);

async function handleSubmit(hasNext: boolean) {
  try {
    const values = await validate();
    setModalProps({ confirmLoading: true });
    // TODO custom api
    if (unref(isUpdate)) {
      await editSysDictData({ ...values });
      createMessage.success(t('修改成功'));
    } else {
      await addSysDictData({ ...values, typeId: props.typeId });
      createMessage.success(t('保存成功'));
    }
    if (hasNext) {
      resetFields();
    } else {
      closeModal();
    }
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>
